<template>
  <div
    v-show="visibleMarker || visiblePopover"
    :id="rootId"
    class="ai-overlay"
    :style="{ top: top + 'px', left: left + 'px' }"
    @mousedown.stop
  >
    <button
      v-show="visibleMarker"
      class="ai-inline-button"
      type="button"
      @mousedown.prevent
      @click="emit('open')"
    >
      AI
    </button>

    <div v-show="visiblePopover" class="ai-popover" :style="{ left: popoverOffsetLeft + 'px', width: popoverWidth + 'px' }">
      <input
        class="ai-input"
        :value="query"
        placeholder="询问 AI：描述你想要生成或修改的内容..."
        @input="onInput"
        @keydown.stop.prevent.exact.enter="emit('submit')"
        @keydown.stop.exact.esc="emit('close')"
        ref="inputRef"
      />
      <div class="ai-hint">
        按 Enter 提交 · Esc 关闭。AI 会基于当前行进行生成或补全。
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue';

const props = defineProps({
  rootId: { type: String, required: true },
  visibleMarker: { type: Boolean, default: false },
  visiblePopover: { type: Boolean, default: false },
  top: { type: Number, default: 0 },
  left: { type: Number, default: 32 },
  popoverOffsetLeft: { type: Number, default: 0 },
  popoverWidth: { type: Number, default: 480 },
  query: { type: String, default: '' },
});

const emit = defineEmits(['open', 'close', 'update:query', 'submit']);

const inputRef = ref(null);

const onInput = (e) => emit('update:query', e.target.value);

watch(() => props.visiblePopover, async (val) => {
  if (val) {
    await nextTick();
    if (inputRef.value) inputRef.value.focus();
  }
});

onMounted(async () => {
  if (props.visiblePopover) {
    await nextTick();
    if (inputRef.value) inputRef.value.focus();
  }
});
</script>

<style scoped>
.ai-overlay {
  position: absolute;
  pointer-events: none;
  z-index: 10;
  /* 相对于 editable-wrapper 定位 */
}

.ai-inline-button {
  pointer-events: auto;
  appearance: none;
  border: 1px solid #e5e7eb;
  background: #ffffff;
  color: #111827;
  border-radius: 14px;
  height: 24px;
  padding: 0 10px;
  font-size: 12px;
  line-height: 22px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
  cursor: pointer;
  position: relative;
  z-index: 210; /* 保持在浮窗之上可见 */
}

.ai-inline-button:hover {
  background: #f9fafb;
}

.ai-popover {
  position: absolute;
  top: -2px; /* 轻微上移以对齐文本基线 */
  pointer-events: auto;
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 10px 12px 8px 12px;
  box-shadow: 0 8px 24px rgba(0,0,0,0.1);
  z-index: 205;
}

.ai-input {
  width: 100%;
  display: block;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 8px 10px;
  box-sizing: border-box;
  font-size: 14px;
  outline: none;
}

.ai-input:focus {
  border-color: #93c5fd;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.ai-hint {
  margin-top: 6px;
  font-size: 12px;
  color: #6b7280;
}
</style> 